package com.example.demo.services.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Attachment;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.demo.dao.PlatId_ProcessInstanceIdMapper;
import com.example.demo.dao.PlatMapper;
import com.example.demo.dao.ProcessinstanceFileHistoryMapper;
import com.example.demo.dao.ProcessinstanceFileMapper;
import com.example.demo.dao.ProjectId_processInstanceIdMapper;
import com.example.demo.dao.Project_detailsMapper;
import com.example.demo.dao.Project_remarksMapper;
import com.example.demo.dao.Project_typeMapper;
import com.example.demo.dao.SysuserMapper;
import com.example.demo.domain.PageBean;
import com.example.demo.domain.Plat;
import com.example.demo.domain.PlatId_ProcessInstanceId;
import com.example.demo.domain.ProcessinstanceFile;
import com.example.demo.domain.ProcessinstanceFileHistory;
import com.example.demo.domain.Project;
import com.example.demo.domain.ProjectId_processInstanceId;
import com.example.demo.domain.Project_details;
import com.example.demo.domain.Project_remarks;
import com.example.demo.domain.Project_type;
import com.example.demo.domain.Sysuser;
import com.example.demo.services.ActivitiService;
import com.example.demo.util.FileUtils;
import com.example.demo.util.MergeFileUtils;
import com.example.demo.util.Util;
import com.github.pagehelper.PageHelper;

@Service
@Transactional
public class ActivitiServiceImpl implements ActivitiService {

	@Autowired
	ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
	@Autowired
	private Project_detailsMapper project_detailsMapper;
	@Autowired
	private SysuserMapper sysuserMapper;
	@Autowired
	private Project_typeMapper project_typeMapper;
	@Autowired
	private Project_remarksMapper project_remarksMapper;
	@Autowired
	private ProjectId_processInstanceIdMapper projectId_processInstanceIdMapper;
	@Autowired
	private ProcessinstanceFileMapper processinstanceFileMapper;
	@Autowired
	private ProcessinstanceFileHistoryMapper processinstanceFileHistoryMapper;
	@Autowired
	private PlatId_ProcessInstanceIdMapper platId_ProcessInstanceIdMapper;
	@Autowired
	private PlatMapper platMapper;
	
	
	/**
	 * 	查询所有进行中的任务
	 * @author hc
	 * @param Map <String, Object> map
	 * @return PageBean<Map <String, Object>> 
	 */
	public PageBean<Map <String, Object>> taskListAll(Map<String, Object> map){
		List<Map<String,Object>> listMap = new ArrayList<Map<String, Object>>();
		Map<String,Object> taskmap = null;

		Long count = processEngine.getTaskService()//
				.createTaskQuery().count();//查询总记录条数
		List<Task> list = processEngine.getTaskService()//与正在执行的任务管理相关的Service
				.createTaskQuery()//创建任务查询对象
				.orderByTaskCreateTime().desc()
				.listPage( ((int) map.get("pageNum") - 1) * 10, (int) map.get("pageSize"));
		
		if(list!=null && list.size() >0){
			for(Task task:list){
				taskmap = new HashMap();
				taskmap.put("task_id", task.getId());
				taskmap.put("processNode",task.getName());
				taskmap.put("processInstanceId",task.getProcessInstanceId());
				taskmap.put("createTime", Util.currentTime(task.getCreateTime()));
				taskmap.put("assignee", sysuserMapper.findById(task.getAssignee()));
				//根据实例id 查询 项目信息然后存入map
				Project_details project = project_detailsMapper.queryProject(task.getProcessInstanceId());
				if(project != null &&  !"".equals(project)) {
					taskmap.put("projectName", project.getName());
					taskmap.put("type_id", project.getType());
				}
				listMap.add(taskmap);
			}
		}
		PageBean pb = new PageBean((Integer)map.get("pageNum"), (Integer)map.get("pageSize"), Integer.parseInt(String.valueOf(count)));
		pb.setList(listMap);
    	return pb;
	}
	
	/**
	 * 	查询用户进行中的任务
	 * @author hc
	 * @param Map <String, Object> map
	 * @return PageBean<Map <String, Object>> 
	 */
	public PageBean<Map <String, Object>> taskList(Map<String, Object> map){
		PageHelper.startPage((Integer)map.get("pageNum"), (Integer)map.get("pageSize")); 
		List<Map<String, Object>> his = projectId_processInstanceIdMapper.queryRuntimeList(map);
		//获取起始记录条数
		PageBean pb = new PageBean((Integer)map.get("pageNum"), (Integer)map.get("pageSize"), projectId_processInstanceIdMapper.queryRuntimeListCount(map));
		pb.setList(his);
    	return pb; 
	}
	
	/**
	 * 	完成任务
	 * @author hc
	 * @param String task_id, String approval, int user_id
	 * @return
	 */
	public Map <String, Object> finishTask(Map <String, Object> map){
		Map<String, Object> result = new HashMap();
		if(Integer.parseInt((String) map.get("approval")) == 0) {
			TaskService taskService = processEngine.getTaskService();
			
			Project_remarks project_remarks = new Project_remarks();
			project_remarks.setNode_name((String) map.get("node_name"));
			project_remarks.setProcessInstance_id((String) map.get("processInstanceId"));
			project_remarks.setRemarks((String) map.get("remarks"));
			project_remarks.setTask_id(Integer.parseInt((String)map.get("task_id")));
			project_remarks.setUser_id(Integer.parseInt(String.valueOf(map.get("user_id"))));
			project_remarksMapper.insert(project_remarks);
			
			//设置下一个任务执行人的流程变量
			//考虑到分发网闸的情况，从前台把分发的人员以数组的形式传过来
			taskService.setVariable( (String) map.get("task_id"), "user_id", String.valueOf(map.get("assignee"))); 
			taskService.setVariable( (String) map.get("task_id"), "approval", map.get("approval"));//o为通过 1为驳回
			taskService.setAssignee( (String) map.get("task_id"), String.valueOf(map.get("user_id")));
			taskService.complete((String) map.get("task_id"));//完成任务
			
			result.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			result.put(Util.MESSAGE, "完成任务成功！");
		} else {
			TaskService taskService = processEngine.getTaskService();
			taskService.setVariable((String) map.get("task_id"), "approval", map.get("approval"));//o为通过 1为驳回
			taskService.complete((String) map.get("task_id"));//完成任务
			result.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			result.put(Util.MESSAGE, "驳回任务成功！");
		}
		return result;
	}
	
	/**
	 * 	新建项目
	 * @author hc
	 * @param Map <String, Object> map
	 * @return Map <String, Object> map
	 */
	public Map <String, Object> newProject(Map <String, Object> map){
		Map<String, Object> result = new HashMap();
		//获取流程定义的key
		Project_type project_type = project_typeMapper.selectByPrimaryKey(Integer.parseInt((String) map.get("type_id")));
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("user_id", map.get("user_id"));
		variables.put("isDepartment", false);
		variables.put("isUpload", false);
		variables.put("rejectStatus", false);
		variables.put("isProcessInstanceRead", false);
		ProcessInstance pi = processEngine.getRuntimeService()//与正在执行的流程实例和执行对象相关的service
						.startProcessInstanceByKey(project_type.getProject_key(),variables);//使用流程定义的KEY启动流程实例
		
		//存入项目基本信息到数据库
		Project_details project = new Project_details();
		project.setName((String) map.get("project_name"));
		project.setProcessinstanceid(pi.getId());
		project.setType(Integer.parseInt((String) map.get("type_id")));
		project_detailsMapper.insert(project);
		
		//流程实例关联项目
		String projectId = map.get("projectId") == null ? "" : (String) map.get("projectId");	
		if(map.get("type_id").equals("1")) {//判断流程类型是跟平台关联还是项目
			PlatId_ProcessInstanceId record = new PlatId_ProcessInstanceId();
			record.setPlatid(projectId);
			record.setProcessinstanceid(pi.getId());
			platId_ProcessInstanceIdMapper.insertSelective(record);
		}else {
			ProjectId_processInstanceId record = new ProjectId_processInstanceId(pi.getId(), Integer.valueOf(projectId));
		    projectId_processInstanceIdMapper.insert(record);
		}
		result.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
		result.put(Util.MESSAGE, "新增项目成功！");
		return result;
	}
	
	/**
	 * 	查询历史活动
	 * @author hc
	 * @param Map <String, Object> map
	 * @return String project_id
	 */
	public List<Map<String, Object>> operationRecord(String project_id){
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = null;
		List<HistoricActivityInstance> list = processEngine.getHistoryService()// act_hi_actinst
						.createHistoricActivityInstanceQuery()//创建历史活动实例的查询
						.processInstanceId(project_id)//
						.orderByHistoricActivityInstanceStartTime().asc()//
						.list();
		for(int i = 0; i < list.size(); i++) {
			//不显示开始、结束、分发等节点
			if("startEvent".equals(list.get(i).getActivityType()) || "exclusiveGateway".equals(list.get(i).getActivityType()) || "parallelGateway".equals(list.get(i).getActivityType()) || "endEvent".equals(list.get(i).getActivityType())){
				continue;
			}
			map = new HashMap();
			if (list.get(i).getAssignee() != null && !"".equals(list.get(i).getAssignee())) {
				map.put("assignee", sysuserMapper.findById(list.get(i).getAssignee()));
			} else {
				map.put("assignee", "系统分发");
			}
			if (list.get(i).getEndTime() != null && !"".equals(list.get(i).getEndTime())) {
				map.put("endTime", Util.currentTime(list.get(i).getEndTime()));
			}
			map.put("activityName", list.get(i).getActivityName());
			map.put("startTime", Util.currentTime(list.get(i).getStartTime()));
			result.add(map);
		}
		return result;
	}
	
//	/**
//	 * 	查询历史流程记录
//	 * @author hc
//	 * @param PageBean<Map <String, Object>>
//	 * @return List<Map<String, Object>>
//	 */
//	public PageBean<Map <String, Object>> historyProjectList(Map <String, Object> map){
//		PageHelper.startPage((Integer)map.get("pageNum"), (Integer)map.get("pageSize")); 
//		List<Map<String, Object>> his = projectId_processInstanceIdMapper.queryBusinessProcessList(map);
//		//获取起始记录条数
//		PageBean pb = new PageBean((Integer)map.get("pageNum"), (Integer)map.get("pageSize"), projectId_processInstanceIdMapper.queryBusinessProcessListCount(map));
//		pb.setList(his);
//    	return pb;
//	}
	
	/**
	 * 	查询历史流程记录
	 * @author hc
	 * @param PageBean<Map <String, Object>>
	 * @return List<Map<String, Object>>
	 */
	public List<Map<String, Object>> historyProjectList(Map <String, Object> condtions){
		//从会话中取出用户信息
    	Object username = SecurityUtils.getSubject().getPrincipal();
    	//查询用户名称
        Sysuser sysuser = sysuserMapper.findByName(username.toString());
		List<HistoricTaskInstance> taskList = processEngine.getHistoryService().createHistoricTaskInstanceQuery().taskAssignee(sysuser.getId().toString()).list();
    	Set<String> processInstanceSet = new HashSet<String>();
    	List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    	for(HistoricTaskInstance hti : taskList) {   			
    		//ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(hti.getProcessInstanceId()).singleResult();这行代码判断是否是进行中
    		processInstanceSet.add(hti.getProcessInstanceId());

    	}  
    	List<HistoricProcessInstance> lists;
    	if(condtions.get("start_time") == null) {
        	lists = processEngine.getHistoryService().createHistoricProcessInstanceQuery().processInstanceIds(processInstanceSet).orderByProcessInstanceEndTime().desc().list();
    	}else {
        	lists = processEngine.getHistoryService().createHistoricProcessInstanceQuery().processInstanceIds(processInstanceSet).startedAfter(Util.dateStrToDate((String)condtions.get("start_time"))).orderByProcessInstanceEndTime().desc().list();
    	}
    	for(HistoricProcessInstance hpi: lists) {
    		condtions.put("processInstanceId", hpi.getId());
    		Map<String, Object> project_details =  project_detailsMapper.queryProjectTypeName(condtions);
    		if(project_details != null) {
    			Map<String, Object>  map = new HashMap<String, Object>();
    			map.put("START_TIME_", Util.currentTime(hpi.getStartTime()));
    			map.put("END_TIME_", hpi.getEndTime() == null ? "-" : Util.currentTime(hpi.getEndTime()));
    			map.put("processInstanceId", hpi.getId());
    			map.put("name", project_details.get("name"));
    			map.put("status", project_details.get("status"));
    			map.put("type_id", project_details.get("type"));
    			result.add(map);
    		}
    	}   
    	return result;
	}
	
	/**
	 * 	删除项目
	 * @author hc
	 * @param Map <String, Object> map
	 * @return 
	 */
	public void delectExample(Map <String, Object> map) {
		project_detailsMapper.delectExample((String) map.get("processInstanceId"));
		try{
			processEngine.getRuntimeService().deleteProcessInstance((String) map.get("processInstanceId"), "删除原因");//删除流程
		}catch (Exception e) {
			throw e;
			//如果删除已完成的流程上述方法会找不到流程 所以删除已完成的流程时捕获错误就可以了  
		}		
	}
	
	/**
	 * 	添加变量
	 * @author dsh
	 * @param variables, taskId
	 * @return 
	 */
	public void addVariables(Map <String, Object> variables, String taskId, String processInstanceId) {
		TaskService taskService = processEngine.getTaskService();
		
		taskService.setVariablesLocal(taskId, variables);
	}

	
	/**
	 * 	添加附件
	 * @author dsh
	 * @param attachments , taskId
	 * @return 
	 */
	@Override
	public void addAttachments(Map<String, Object> attachments, String taskId, String processInstanceId) {
		TaskService taskService = processEngine.getTaskService();
		String attachmentName = (String)attachments.get("fileName");
		taskService.createAttachment(attachmentName.substring(attachmentName.indexOf(".") + 1), taskId, processInstanceId, attachmentName, "", (String)attachments.get("filePath"));		
	}

	/**
	 * 	完成任务two
	 * @author dsh
	 * @param isAllowed ,taskId, assignee
	 * @return 
	 */
	@Override
	public void finishTaskTwo(Map<String, Object> map) {
		TaskService taskService = processEngine.getTaskService();
		String taskId = (String) map.get("task_id");
		String assignee = (String) map.get("assignee");
		String approval = (String) map.get("approval");
		String department = (String) map.get("department");
		if(assignee==null || assignee.equals("")) {
			if(department!=null) {
				if(!department.equals("")) {
					assignee = sysuserMapper.selectMinister(department) + "";
				}
			}					
		}
		taskService.setVariable(taskId, "approval", approval);
		taskService.setVariable(taskId, "user_id", assignee);
		taskService.setVariable(taskId, "isDepartment", false);
		taskService.setVariable(taskId, "isUpload", false);
		taskService.setVariable(taskId, "rejectStatus", false);
		taskService.setVariable(taskId, "isProcessInstanceRead", false);//初始化未读
		taskService.setVariableLocal(taskId, "approval", approval);
		taskService.complete(taskId);
	}
	
	/**
	 * 	查找流程实例的历史节点记录
	 * @author dsh
	 * @param processInstanceId
	 * @return 
	 */
	@Override
	public List<Map<String, Object>> findProcessInstanceHistoryRecord(String processInstanceId ) {
		HistoryService historyService = processEngine.getHistoryService();
		TaskService taskService = processEngine.getTaskService();
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		List<HistoricTaskInstance> list = processEngine.getHistoryService()//与历史数据相关的service
				.createHistoricTaskInstanceQuery()//创建历史任务查询实例
				.processInstanceId(processInstanceId)//根据流程查询历史任务
				.orderByHistoricTaskInstanceStartTime().asc()
				.list();
		for(HistoricTaskInstance hpi : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("taskName", hpi.getName());
			map.put("taskId", hpi.getId());
			map.put("taskStartTime",  Util.currentTime(hpi.getStartTime()));		
			map.put("assignee", sysuserMapper.findById(hpi.getAssignee()));
			map.put("userId", hpi.getAssignee());
			List<HistoricVariableInstance> taskVariables = historyService.createHistoricVariableInstanceQuery().taskId(hpi.getId()).list();
			List<Attachment> attachments = taskService.getTaskAttachments(hpi.getId());	
			//map.put("taskVariables",   taskVariables);获取所有变量
			for(HistoricVariableInstance hvi : taskVariables) {
				map.put(hvi.getVariableName(),   hvi.getValue());
			}			
			map.put("attachments",   attachments);
			resultList.add(map);
		}
		return resultList;
	}

	/**
	 * 	查找taskId的所有附件
	 * @author dsh
	 * @param taskId
	 * @return List<Attachment>
	 */
	@Override
	public List<Attachment> findTaskAttachmentsTable(String taskId) {
		TaskService taskService = processEngine.getTaskService();
		List<Attachment> attachments = taskService.getTaskAttachments(taskId);
		return attachments;
	}
	
	/**
	 * 	根据Id删除附件
	 * @author dsh
	 * @param attachmentId
	 * @return void
	 */
	@Override
	public void deleteAttachmentById(String attachmentId) {
		TaskService taskService = processEngine.getTaskService();
		taskService.deleteAttachment(attachmentId);
	}
	
	/**
	 * 	更改项目状态
	 * @author hc
	 * @param Project_details project_details
	 * @return void
	 */
	public void updateStatus(Project_details project_details) {
		 project_detailsMapper.updateStatus(project_details);
	}
	
	
	/**
	 * 	查询此流程实例关联的所有全局文件
	 * @author dsh
	 * @param processInstanceId 流程实例ID
	 * @return List<ProcessinstanceFile>
	 */
	@Override
	public List<ProcessinstanceFile> findGlobalFIleByPid(String processInstanceId) {
		List<ProcessinstanceFile> processinstanceFiles =  processinstanceFileMapper.selectProcessinstanceFileByPid(processInstanceId);
		return processinstanceFiles;
	}

	
	/**
	 * 	查询此流程实例关联的所有全局文件
	 * @author dsh
	 * @param processInstanceId 流程实例ID, taskId 任务ID
	 * @return void
	 */
	@Override
	public void addGlobalFIle(String processInstanceId, String taskId,String url, String fileName,String processInstanceFileId) {
		ProcessinstanceFile processinstanceFile = new ProcessinstanceFile();
		ProcessinstanceFileHistory processinstanceFileHistory = new ProcessinstanceFileHistory();
		Date date = new Date();
		processinstanceFile.setFilename(fileName);
		processinstanceFile.setProcessinstanceid(processInstanceId);
		processinstanceFile.setUrl(url);
		processinstanceFile.setTaskid(taskId);
		processinstanceFile.setTime(date);
		
		// 从会话中取出用户信息
		Object username = SecurityUtils.getSubject().getPrincipal();
		// 查询用户名称
		Sysuser sysuser = sysuserMapper.findByName(username.toString());
		processinstanceFile.setUserid(sysuser.getId());
		if(processInstanceFileId.equals("")) {//当processInstanceFileId为空时说明不是更新文件
			processinstanceFileMapper.insert(processinstanceFile);
			ProcessinstanceFile id = processinstanceFileMapper.selectProcessinstanceFileByUrl(url);
			processinstanceFileHistory.setFilename(fileName);
			processinstanceFileHistory.setUrl(url);
			processinstanceFileHistory.setTaskid(taskId);
			processinstanceFileHistory.setTime(date);
			processinstanceFileHistory.setUserid(sysuser.getId());
			processinstanceFileHistory.setProcessinstancefileid(id.getId());
			
			processinstanceFileHistoryMapper.insertSelective(processinstanceFileHistory);
		}else {
			processinstanceFile.setId(Integer.valueOf(processInstanceFileId));
			processinstanceFileMapper.updateByPrimaryKeySelective(processinstanceFile);
			processinstanceFileHistory.setFilename(fileName);
			processinstanceFileHistory.setUrl(url);
			processinstanceFileHistory.setTaskid(taskId);
			processinstanceFileHistory.setTime(date);
			processinstanceFileHistory.setUserid(sysuser.getId());
			processinstanceFileHistory.setProcessinstancefileid(Integer.valueOf(processInstanceFileId));
			
			processinstanceFileHistoryMapper.insertSelective(processinstanceFileHistory);
		}
		
		
	}

	/**
	 * 	查询全局文件的所有历史版本
	 * @author dsh
	 * @param processInstanceFileId 全局文件对应的id
	 * @return List<ProcessinstanceFileHistory>
	 */
	@Override
	public List<Map<String, Object>> findSingleGlobalFIleHisById(String processInstanceFileId) {
		List<Map<String, Object>> processinstanceFileHistories = processinstanceFileHistoryMapper.selectByProcessInstanceFileId(processInstanceFileId);
	    return processinstanceFileHistories; 
	}

	/**
	 * 	查询流程实例所有先关的附件
	 * @author dsh
	 * @param processInstanceId 流程实例id
	 * @return List<Attachment>
	 */
	@Override
	public List<Attachment> findAttachmentsTableByPid(String processInstanceId) {
		TaskService taskService = processEngine.getTaskService();
		List<Attachment> attachmentList = new ArrayList<Attachment>();
		List<HistoricTaskInstance> list = processEngine.getHistoryService()//与历史数据相关的service
				.createHistoricTaskInstanceQuery()//创建历史任务查询实例
				.processInstanceId(processInstanceId)//根据流程查询历史任务
				.orderByHistoricTaskInstanceStartTime().asc()
				.list();
		for(HistoricTaskInstance hpi : list) {
			String username = sysuserMapper.findById(hpi.getAssignee());
			List<Attachment> attachments = taskService.getTaskAttachments(hpi.getId());
			for(Attachment atta :attachments) {
				atta.setDescription(username);//因为不能setUserID 所以用description暂时代替操作人
			}
			attachmentList.addAll(attachments);
		}
		return attachmentList;
	}
	
	@Override
	public boolean findRejectStatusByTaskId(String taskId) {
		boolean result = false;
		TaskService taskService = processEngine.getTaskService();
		result = (boolean) taskService.getVariable(taskId, "rejectStatus");  
		return result;
	}
	
	@Override
	public boolean findIsDepartment(String taskId) {
		boolean result = false;
		TaskService taskService = processEngine.getTaskService();
		result = taskService.getVariable(taskId, "isDepartment") == null ? false : (boolean) taskService.getVariable(taskId, "isDepartment");  
		return result;
	}
	
	@Override
	public boolean findIsUpload(String taskId) {
		boolean result = false;
		TaskService taskService = processEngine.getTaskService();
		result = taskService.getVariable(taskId, "isUpload") == null ? false : (boolean) taskService.getVariable(taskId, "isUpload");  
		return result;
	}
	
	/** 
     * 获取下一个用户任务用户组信息  
     * @param String taskId     任务Id信息  
     * @return  下一个用户任务用户组信息  
     * @throws Exception 
     */ 
	@Override
    public Map<String,Object> getNextTaskName(String taskId){ 
		Map<String,Object> result =  new HashMap<String, Object>();
    	boolean equals = false;//判断是否是当前节点
        String nextTaskName = "";//下一节点的名字
        ProcessDefinitionEntity processDefinitionEntity = null;  
          
        String id = null;  
          
        TaskDefinition task = null;  
        
        TaskService taskService = processEngine.getTaskService();
        
          
        //获取流程实例Id信息   
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();  
          
        //获取流程发布Id信息   
        String definitionId = processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();  
          
        processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) processEngine.getRepositoryService())  
                .getDeployedProcessDefinition(definitionId);  
          
        ExecutionEntity execution = (ExecutionEntity)  processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();  
          
        //当前流程节点Id信息   
        String activitiId = execution.getActivityId();   
 
        //获取流程所有节点信息   
        List<ActivityImpl> activitiList = processDefinitionEntity.getActivities();   
        //储存所有出口节点的信息
        List<Map<String,String>> conditions = new ArrayList<Map<String,String>>();
        //遍历所有节点信息   
        for(ActivityImpl activityImpl : activitiList){          	
            id = activityImpl.getId();     
            if(equals) {
            	nextTaskName = (String) activityImpl.getProperty("name");	
            	result.put("nextTaskName", nextTaskName);
               break;
            }
            
            // 找到当前节点信息  
            if (activitiId.equals(id)) {  
            	 List<PvmTransition>  pvmTransitionList = activityImpl.getOutgoingTransitions();
            	 if(pvmTransitionList.size() > 1) {
            		  //获取下一个节点信息 
   	              for(PvmTransition pvmTransition : pvmTransitionList) {
   		        		Map<String,String> map = new HashMap<String, String>();
   		        		String condition =  (String) pvmTransition.getProperty("conditionText");
   		        		if(condition!=null&&!condition.equals("")) {
   		        			PvmActivity pvmActivity = pvmTransition.getDestination();
   	   		        		String taskName = (String) pvmActivity.getProperty("name");
   	   		        		condition = condition.replace("\"", "");
   	   		        		map.put("condition", condition.substring(condition.indexOf("==")+2,condition.length()-1));
   	   		        		map.put("taskName", taskName);
   	   		        		if(!map.get("condition").toString().equals("0")) {
   	   		        			conditions.add(map);
   	   		        		}
   		        		}   		        		
   	        	  }
            	 }                
            	equals = true;

            }  
        }  
        result.put("conditions", conditions);
        return result;  
    }  
    
    public void findAllProcessInstance(Map<String, Object> condtions) {
    	processEngine.getHistoryService()
    	              .createHistoricProcessInstanceQuery()
    	              .processDefinitionKeyIn(new ArrayList<String>())
    	              .list();
    }

	@Override
	public Map<String, Object> findProcessInstanceVariables(String taskId) {
		TaskService taskService = processEngine.getTaskService();
		Map<String, Object> variables = taskService.getVariables(taskId);
		return variables;
	}

	@Override
	public void changeIsProcessInstanceRead(String taskId) {
		processEngine.getTaskService().setVariable(taskId, "isProcessInstanceRead", true);		
	}

	@Override
	public int deleteGlobalFile(int id, String url) {
		int result = processinstanceFileMapper.deleteByPrimaryKey(Integer.valueOf(id));
		FileUtils.deleteFile(url);
		return result;
	}		
}
